<template>
    <div class="supplier_form_container">
        <el-tabs v-model="activeName" @tab-click="handleClickTabs">
            <el-tab-pane label="基本资料" name="first" class="first">
                <el-form ref="supplierForm" :model="formData" :rules="rules" label-width="120px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="分类" prop="supplier_type_sid">
                                <tree-select v-model="formData.supplier_type_sid" v-bind.sync="treeSelectOption"
                                             @input="selectTree" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="编码" prop="code">
                                <el-input v-model="formData.code" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="formData.name" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="简称" prop="short_name">
                                <el-input v-model="formData.short_name" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="助记码" prop="search_code">
                                <el-input v-model="formData.search_code" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="社会信用代码">
                                <el-input v-model="formData.social_credit_code" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="开户银行">
                                <el-input v-model="formData.deposit_bank" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="银行账号">
                                <el-input v-model="formData.bank_account" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="开户姓名">
                                <el-input v-model="formData.bank_account_name" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="电话">
                                <el-input v-model="formData.phone" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="传真">
                                <el-input v-model="formData.faxes" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="法人">
                                <el-input v-model="formData.legal_person" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="法人电话">
                                <el-input v-model="formData.legal_person_phone" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="等级">
                                <el-select v-model="formData.level" clearable
                                           placeholder="请选择" style="width: 100%">
                                    <el-option v-for="(item, index) in levelOptions" :key="index"
                                               :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="交货方式">
                                <el-input v-model="formData.delivery_mode" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="月产能">
                                <el-input onkeyup="this.value=this.value.replace(/\D|^0/g,'')"
                                          onafterpaste="this.value=this.value.replace(/\D|^0/g,'')"
                                          v-model="formData.month_capacity" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="结算方式">
                                <el-select v-model="formData.pay_mode" placeholder="请选择"
                                           style='width: 100%;'>
                                    <el-option label="现结" :value="1" />
                                    <el-option label="月结" :value="2" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="地址">
                                <el-input v-model="formData.address" autocomplete="off" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24" style="text-align: right;padding-right: 3em;">
                            <el-button class="btn mr3" @click="handleClose()">取 消</el-button>
                            <el-button class="btn" type="primary" @click="confirm()" v-btnLoading>确 定</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <!-- 监听高度变化 -->
                <resize-sensor initial @resize="handleResizeEvent" />
            </el-tab-pane>
            <el-tab-pane label="联系人" name="second" class="second">
                <div class="tab_container" :style="tabContainerStyle">
                    <div class="ss-col-12 item_add flex-c" v-if="!$utils.isNotEmpty(formData.sid)">
                        <el-card class="flex-c ss-col-12" shadow="never">
                            <span>请先保存基本资料</span>
                        </el-card>
                    </div>
                    <div v-else class="ss-col-12 mb10 item_add flex-c"
                         @click="handelAddContractPerson()">
                        <el-card class="flex-c ss-col-12 add_card">
                            <i class="fs30 el-icon-circle-plus-outline"></i>
                            <span>新建联系人</span>
                        </el-card>
                    </div>
                    <div class="contract_card_container" :style="cardContainerStyle">
                        <template v-for="(item, index) in contractPersonList">
                            <contract-person-card :key="index" :data="item" :ref="`contactPersonCard${index}`"
                                                  show-default @event="handlePersonCardEvent" />
                        </template>
                    </div>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import ResizeSensor from 'vue-resize-sensor'

export default {
    name: "SupplierForm",
    components: {
        ResizeSensor,
        ContractPersonCard: () => import('../components/ContractPersonCard'),
    },
    props: {
        propsData: {
            type: Object,
            default() {
                return {
                    init: true,
                };
            },
        },
        selectBottom: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            activeName: 'first',
            levelOptions: [
                {
                    value: "A",
                    label: "等级A",
                },
                {
                    value: "B",
                    label: "等级B",
                },
                {
                    value: "C",
                    label: "等级C",
                },
            ],
            treeSelectOption: {
                defaultExpandLevel: -1,
                clearable: false,
                zIndex: 999999,
                appendToBody: true,
                options: [],
            },
            rules: {
                code: [
                    { required: true, message: "请输入编码", trigger: "blur" },
                    {
                        // pattern: /^[A-Za-z0-9+-_.]{1,32}$/,
                        // message:
                        //   "最大32位字符，大小写英文、数字或者以下特殊字符（+-_.），不能包含特殊字符",
                        max: 32,
                        message: "最大 32 位字符，内容过长，请删减",
                        trigger: "blur",
                    },
                ],
                name: [
                    { required: true, message: "请输入名称", trigger: "blur" },
                    //目前只兼容中文、大小写英文、数字
                    {
                        // pattern: /^[A-Za-z0-9\u4e00-\u9fa5]{1,50}$/,
                        // message:
                        //   "最大 50 位大小写英文、数字或者其它地区语言字符，不能包含特殊字符",
                        max: 50,
                        message: "最大 50 位字符，内容过长，请删减",
                        trigger: "blur",
                    },
                ],
                supplier_type_sid: [
                    { required: true, message: "请选择分类", trigger: "change" },
                ],
                //简称不需要必填
                short_name_1: [
                    { required: true, message: "请输入简称", trigger: "blur" },
                    { pattern: /^[A-Za-z0-9]/, message: "只能录入英文或者数字", trigger: "blur" },
                ],
                level: [ { required: true, message: "请选择分类", trigger: "change" } ],
            },
            formData: {},
            contractPersonList: [],
        };
    },
    computed: {
        tabContainerStyle() {
            return {
                minHeight: `${ this.height }px`,
            };
        },
        cardContainerStyle() {
            let height = $(this.getActiveTabsContainer()).height() * 0.9 - 178;
            return {
                maxHeight: `${ height }px`,
            };
        },
    },
    watch: {
        propsData: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        handleResizeEvent(e) {
            this.height = e.height;
        },
        async init() {
            const _this = this;
            if (_this.propsData.init) {
                return;
            }
            _this.activeName = 'first';
            if (_this.$refs.supplierForm) {
                _this.$refs.supplierForm.clearValidate();
            }
            _this.formData = $.extend({}, {pay_mode: 1}, _this.propsData.row);
            _this.initTreeList();
            if (!_this.$utils.isNotEmpty(_this.formData.sid)) {
                _this.generateCode();
            } else {
                _this.initContractPersonList();
            }
        },
        initTreeList() {
            const _this = this;
            if (_this.$utils.isNotEmptyList(_this.propsData.treeList)) {
                let options = _this.transferTreeData(_this.propsData.treeList);
                _this.treeSelectOption = $.extend({}, _this.treeSelectOption, {
                    options: [{ id: '-1', label: '未分类' }].concat(options),
                    value: _this.formData.client_type_sid,
                });
                return;
            }
            _this.fetchData(_this.$api.API_FindSysSupplierTypeTree).then(result => {
                let options = _this.transferTreeData(result.data);
                _this.treeSelectOption = $.extend({}, _this.treeSelectOption, {
                    options: [{ id: '-1', label: '未分类' }].concat(options),
                    value: _this.formData.client_type_sid,
                });
            }).catch(() => {
            });
        },
        transferTreeData(datas) {
            const _this = this;
            let list = [];
            if (_this.$utils.isNotEmptyList(datas)) {
                list = datas.map(item => {
                    let obj = {};
                    obj.id = item.sid;
                    obj.label = item.name;
                    obj.isDefaultExpanded = true;
                    if (_this.$utils.isNotEmptyList(item.children)) {
                        obj.children = _this.transferTreeData(item.children);
                    }
                    return obj;
                });
            }
            return list;
        },
        generateCode() {
            const _this = this;
            return _this.fetchData(_this.$api.API_GetAutoOrderCode, {
                rule_code: 'base_supplier',
            }).then(result => {
                _this.oldCode = result.data;
                _this.formData = $.extend({}, _this.formData, {
                    code: result.data,
                });
            }).catch(() => {
            });
        },
        initContractPersonList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindSysContractPersons, {
                org_sid: _this.formData.sid,
            }).then(result => {
                _this.contractPersonList = _this.resetIndex(result.data);
                _this.setIsDefault(_this.contractPersonList, _this.formData.contract_person_sid);
            }).catch(() => {
            });
        },
        setIsDefault(list, value) {
            const _this = this;
            if (!_this.$utils.isNotEmptyList(list)) {
                return;
            }
            if (!_this.$utils.isNotEmpty(value)) {
                return;
            }
            list.forEach(item => {
                _this.$set(item, 'is_default', item.sid === value);
            });
            _this.$forceUpdate();
        },
        handleClickTabs(tab) {
            const _this = this;
            if (tab.name === 'first') {
                return;
            }
            if (_this.$utils.isNotEmpty(_this.formData.sid)) {
                return;
            }
            _this.$confirm("请先保存基本资料", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                showCancelButton: false,
            }).then(() => {
                _this.$set(_this, 'activeName', 'first');
                _this.$forceUpdate();
            }).catch(() => {
            });
        },
        selectTree(value) {
            this.formData = $.extend({}, this.formData, {
                supplier_type_sid: value,
            });
            if (this.$refs.supplierForm) {
                this.$refs.supplierForm.clearValidate('supplier_type_sid');
            }
        },
        handelAddContractPerson() {
            const _this = this;
            let list = _this.contractPersonList.map(item => $.extend({}, item));
            let filterAdd = list.filter(item => _this.$utils.isEmpty(item.sid));
            if (_this.$utils.isNotEmptyList(filterAdd)) {
                return;
            }
            let data = {
                name: '',
                phone: '',
                email: '',
                qq: '',
                org_sid: _this.formData.sid,
            };
            list.unshift(data);
            _this.contractPersonList = _this.resetIndex(list);
        },
        handlePersonCardEvent(event) {
            const _this = this;
            if (event.type === 'refresh') {
                _this.initContractPersonList();
                return;
            }
            if (event.type === 'del') {
                let list = _this.contractPersonList.map(item => $.extend({}, item));
                list = list.filter(item => item._index !== event.data._index);
                _this.contractPersonList = _this.resetIndex(list);
                return;
            }
            if (event.type === 'setDefault') {
                _this.formData = $.extend({}, _this.formData, {
                    contract_person_sid: event.data.is_default ? event.data.sid : '',
                });
                _this.confirm(true, event.del_default);
            }
        },
        handleClose() {
            this.$emit('event', 'closeDialog');
        },
        async confirm(setDefault, del_default) {
            const _this = this;
            let valid = await _this.validateForm('supplierForm');
            if (valid) {
                let subData = $.extend({}, _this.formData);
                if (!setDefault) {
                    subData.is_auto_code = _this.formData.code === _this.oldCode;
                }
                return _this.fetchData(_this.$api.API_SaveSysSupplier, subData).then(result => {
                    _this.formData = result.data || {};
                    if (setDefault || del_default) {
                        _this.initContractPersonList();
                    }
                    if (!del_default) {
                        _this.$message.success('保存成功！');
                    }
                    _this.$emit('event', { type: 'refresh', data: _this.formData });
                    if (_this.selectBottom) {
                        _this.$emit('event', 'closeDialog');
                    }
                    return true;
                }).catch(() => {
                    return false;
                });
            }
            return valid;
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.supplier_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .btn {
        width: 96px;
        height: 36px;

        &.mr3 {
            margin-right: 3em;
        }
    }

    /deep/ .tab_container {
        .item_add {
            cursor: pointer;

            .add_card {
                .el-card__body {
                    display: flex;
                    align-items: center;
                    flex-direction: column;
                }
            }
        }

        .contract_card_container {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            width: 100%;
            overflow-y: auto;
        }

        .el-row {
            height: 100%;

            .el-col {
                height: 100%;

                .card_container {
                    display: flex;
                    justify-content: space-between;
                    flex-wrap: wrap;
                    width: 100%;
                    overflow-y: auto;
                }
            }
        }
    }
}
</style>
